package api

import (
	"fmt"
	"network_study3/src/server/moudle"
)

/**
 * 登录
 */
func Login(userName string, password string) (string, error) {
	// 查找所有用户
	sysUserArr := moudle.SysUserAll()

	var loginFlag bool = false
	for _, sysUser := range sysUserArr {
		if sysUser.UserName == userName && sysUser.Password == password {
			loginFlag = true //查询到用户
			break
		}
	}

	if !loginFlag {
		return "", fmt.Errorf("登录失败：账号密码不正确！")
	}

	return fmt.Sprintf("%s, 登录成功", userName), nil
}

/**
 * 注册
 */
func Register(sysUser moudle.SysUser) (string, error) {
	if sysUser.Name == "" {
		return "", fmt.Errorf("姓名不能为空！")
	}
	if sysUser.UserName == "" {
		return "", fmt.Errorf("用户名不能为空！")
	}
	if sysUser.Phone == "" {
		return "", fmt.Errorf("手机号不能为空！")
	}
	if sysUser.Password == "" {
		sysUser.Password = "123456"
	}

	// 校验 用户名和手机号 不能重复
	sysUserArr := moudle.SysUserAll()
	oldLen := len(sysUserArr)
	for i := 0; i < oldLen; i++ {
		if sysUser.UserName == sysUserArr[i].UserName {
			return "", fmt.Errorf("用户名不能重复：%s", sysUser.UserName)
			break
		}
	}

	for _, v := range moudle.SysUserAll() {
		if sysUser.Phone == v.Phone {
			return "", fmt.Errorf("手机号不能重复：%s", sysUser.Phone)
			break
		}
	}

	// 添加用户
	moudle.SysUserAdd(sysUser)
	if len(moudle.SysUserAll()) <= oldLen {
		return "", fmt.Errorf("注册失败！")
	}
	return sysUser.UserName, nil
}

/**
 * 注销用户
 */
func Cancel(id int) {
	moudle.SysUserRemove(id)
}
